package com.fw.application.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.UserController;
import com.fw.common.Builder;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.vo.CityCodeSortVo;
import com.fw.system.web.model.vo.CountrySortVo;
import com.fw.system.web.model.vo.SortUpDataInterfaceVo;
import com.fw.system.web.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.fw.mes.ResultUtils.success;

@RestController
@RequestMapping("/web/sort")
@CrossOrigin
@Api(tags = "统计排行相关")
public class SortCountController implements UserController {


    @Autowired
    private ITbCityCodeService cityCodeService;
    @Autowired
    private ITbUserCityJoinService joinService;
    @Autowired
    private ITbUserService userService;
    @Autowired
    private ITbConutrySortService conutrySortService;
    @Autowired
    private ITbFriendsService friendsService;
    @Autowired
    private ITbWechatFootService wechatFootService;

    @GetMapping("/citySort")
    @ApiOperation("城市战队PK排行榜")
    public Result citySort() {

        List<CityCodeSortVo> voList = cityCodeService.list(Wrappers.<TbCityCode>lambdaQuery().ne(TbCityCode::getSortCode, 0)).stream().map(map -> {
            CityCodeSortVo build = Builder.of(CityCodeSortVo::new).build();
            BeanUtil.copyProperties(map, build);
            build.setFootNum(0);
            build.setUserNum(joinService.count(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getIsType, 1).eq(TbUserCityJoin::getCityCode, map.getId())));
            List<String> userIds = joinService.list(Wrappers.<TbUserCityJoin>lambdaQuery()
                    .eq(TbUserCityJoin::getIsType, 1).eq(TbUserCityJoin::getCityCode, map.getId()))
                    .parallelStream()
                    .map(m -> m.getUserId()).collect(Collectors.toList());
            if (userIds.size() > 0) {
                int sum = userService.list(Wrappers.<TbUser>lambdaQuery().ne(TbUser::getCountFool, 0).in(TbUser::getId, userIds)).
                        parallelStream().mapToInt(TbUser::getCountFool).sum();
                build.setFootNum(sum);
            }
            return build;
        }).sorted(Comparator.comparing(CityCodeSortVo::getFootNum).reversed()).collect(Collectors.toList());
        return success(voList);
    }


    //全国排行
    @GetMapping("/countrySort")
    @ApiOperation("查询全国排行")
    public Result countrySort(@RequestParam(defaultValue = "1", required = false) Integer pageNum, @RequestParam(defaultValue = "10", required = false) Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<TbConutrySort> list = conutrySortService.list(Wrappers.<TbConutrySort>lambdaQuery().orderByDesc(TbConutrySort::getCountFool).orderByDesc(TbConutrySort::getNowCountCity).orderByAsc(TbConutrySort::getCountTime));
        PageInfo<TbConutrySort> pageInfo = new PageInfo<>(list);
        return success(pageInfo);
    }


    //好友排行
    @GetMapping("/friSort")
    @ApiOperation("查询好友排行")
    public Result friSort() {
        String userId = this.getUser().getId();
        List<String> ids = friendsService.list(Wrappers.<TbFriends>lambdaQuery()
                .eq(TbFriends::getUserId, userId)).stream()
                .map(TbFriends::getFriendsId).collect(Collectors.toList());
        ids.add(userId);
        List<String> userIds = userService.list(Wrappers.<TbUser>lambdaQuery().in(TbUser::getId, ids).ge(TbUser::getNowCityCount, 1)).stream().map(TbUser::getId).collect(Collectors.toList());
        List<CountrySortVo> collect = userIds.stream().map(map -> {
            CountrySortVo build = Builder.of(CountrySortVo::new).build();
            TbWechatFoot tbWechatFoot = wechatFootService.list(Wrappers.<TbWechatFoot>lambdaQuery().eq(TbWechatFoot::getUserId, map).orderByAsc(TbWechatFoot::getCreateTime)).get(0);
            TbUserCityJoin tbUserCityJoin = joinService.list(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getUserId, map).orderByDesc(TbUserCityJoin::getCreateTime)).get(0);
            //计算时差毫秒
            build.setCountTime(Duration.between(tbWechatFoot.getCreateTime(), tbUserCityJoin.getCreateTime()).toMillis());
            build.setCountDayTime(DateUtil.formatBetween(build.getCountTime(), BetweenFormatter.Level.MILLISECOND));
            TbUser user = userService.getById(map);
            TbUserCityJoin one = joinService.getOne(Wrappers.<TbUserCityJoin>lambdaQuery().eq(TbUserCityJoin::getUserId, user.getId()).eq(TbUserCityJoin::getIsType, 1));
            build.setCityName(cityCodeService.getById(one.getCityCode()).getCityName());
            build.setCountFool(user.getCountFool());
            build.setNowCountCity(user.getNowCityCount());
            build.setNickName(user.getNickName());
            build.setImgUrl(user.getImgUrl());
            build.setUserId(user.getId());
            return build;
        }).sorted(Comparator.comparing(CountrySortVo::getCountFool)
                .reversed()
                .thenComparingLong(CountrySortVo::getCountTime))
                .collect(Collectors.toList());
        return success(collect);
    }


    @GetMapping("/sortUpDataInterface")
    @ApiOperation("查询排行榜上半部分接口")
    public Result sortUpDataInterface() {

        TbUser user = this.getUser();
        SortUpDataInterfaceVo build = Builder.of(SortUpDataInterfaceVo::new).build();
        build.setBomb(user.getBomb());
        build.setImgUrl(user.getImgUrl());
        build.setShield(user.getShield());
        build.setNowCityCount(user.getNowCityCount());
        build.setWechatFool(user.getCountFool());//更改为累计
        if (user.getNowCityCount() == 0) {
            build.setCountrySort(0);
        } else {
            int i = conutrySortService.list(Wrappers.<TbConutrySort>lambdaQuery()
                    .orderByDesc(TbConutrySort::getCountFool)
                    .orderByAsc(TbConutrySort::getCountTime))
                    .stream().map(map -> map.getUserId())
                    .collect(Collectors.toList())
                    .indexOf(user.getId());
            build.setCountrySort(i + 1);
        }
        return success(build);
    }




}
